<template>
  <div
    class="drawing-canvas-container relative max-h-[80vh] md:max-h-none"
    :class="containerClass"
  >
    <div
      class="canvas-wrapper relative w-full aspect-[4/3]"
      ref="canvasWrapper"
    >
      <canvas
        ref="canvas"
        :width="canvasWidth"
        :height="canvasHeight"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        @touchstart="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="stopDrawing"
        style="transform-origin: top left"
        :style="{ transform: `scale(${scale})` }"
        class="absolute top-0 left-0 border border-gray-300 rounded-lg bg-white cursor-crosshair touch-none"
      />

      <!-- 绘画工具栏 -->
      <div
        class="drawing-tools"
        :class="toolsClass"
        v-show="props.isDrawer && !props.disabled"
      >
        <div class="flex items-center gap-2 bg-white rounded-lg shadow-md p-2">
          <!-- 颜色选择 -->
          <div class="flex gap-1">
            <button
              v-for="color in colors"
              :key="color"
              @click="currentColor = color"
              :class="[
                'w-8 h-8 rounded-full border-2 transition-all',
                currentColor === color
                  ? 'border-gray-800 scale-110'
                  : 'border-gray-300',
              ]"
              :style="{ backgroundColor: color }"
            />
          </div>

          <!-- 画笔大小 -->
          <div class="flex items-center gap-2 ml-4">
            <span class="text-sm text-gray-600">粗细:</span>
            <input
              v-model="brushSize"
              type="range"
              min="2"
              max="20"
              class="w-16"
            />
            <span class="text-sm text-gray-600 w-6">{{ brushSize }}</span>
          </div>

          <!-- 撤回按钮 -->
          <button
            @click="undoLastStroke"
            :disabled="!canUndo"
            class="p-2 rounded-lg hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
            title="撤回"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              class="h-6 w-6"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M3 10h10a4 4 0 0 1 4 4v2M3 10l6 6m-6-6l6-6"
              />
            </svg>
          </button>

          <!-- 清除按钮 -->
          <button
            @click="clearCanvas"
            class="ml-4 px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 transition-colors text-sm"
          >
            清除
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from "vue";
import { useGameStore } from "../stores/game";
import type { DrawPoint, DrawStroke } from "../types/game";

const props = defineProps<{
  isDrawer: boolean;
  disabled?: boolean;
}>();

const emit = defineEmits<{
  strokeAdded: [stroke: DrawStroke];
  canvasCleared: [];
}>();

// 基础画布尺寸
const BASE_WIDTH = 800;
const BASE_HEIGHT = 600;

// 计算缩放比例
const scale = ref(1);
const updateScale = () => {
  if (!canvasWrapper.value) return;
  const containerWidth = canvasWrapper.value.clientWidth;
  scale.value = containerWidth / BASE_WIDTH;
};

const gameStore = useGameStore();

// Canvas相关
const canvas = ref<HTMLCanvasElement>();
const canvasWrapper = ref<HTMLDivElement>();
const ctx = ref<CanvasRenderingContext2D>();

// 绘画状态
const isDrawing = ref(false);
const currentStroke = ref<DrawPoint[]>([]);
const currentColor = ref("#000000");
const brushSize = ref(3);

// 响应式尺寸
const canvasWidth = ref(800);
const canvasHeight = ref(600);
const isMobile = ref(false);

// 颜色选项
const colors = [
  "#000000",
  "#FF0000",
  "#00FF00",
  "#0000FF",
  "#FFFF00",
  "#FF00FF",
  "#00FFFF",
  "#FFA500",
  "#800080",
  "#FFC0CB",
  "#A52A2A",
  "#808080",
];

// 响应式样式类
const containerClass = computed(() => ({
  "mobile-layout": isMobile.value,
  "desktop-layout": !isMobile.value,
}));

const toolsClass = computed(() => ({
  "tools-mobile": isMobile.value,
  "tools-desktop": !isMobile.value,
}));

// 检测设备类型和设置画布尺寸
const updateCanvasSize = () => {
  if (!canvasWrapper.value) return;

  const wrapper = canvasWrapper.value;
  const rect = wrapper.getBoundingClientRect();

  isMobile.value = window.innerWidth < 768;

  if (isMobile.value) {
    // 手机端：画布占屏幕上半部分
    canvasWidth.value = Math.min(rect.width - 20, window.innerWidth - 40);
    canvasHeight.value = Math.min(400, window.innerHeight * 0.5);
  } else {
    // 电脑端：更大的画布
    canvasWidth.value = Math.min(800, rect.width - 40);
    canvasHeight.value = Math.min(600, window.innerHeight * 0.7);
  }
};

// 获取鼠标/触摸位置
const getEventPos = (event: MouseEvent | TouchEvent) => {
  if (!canvas.value) return { x: 0, y: 0 };

  const rect = canvas.value.getBoundingClientRect();
  const scaleX = canvas.value.width / rect.width;
  const scaleY = canvas.value.height / rect.height;

  let clientX, clientY;

  if (event instanceof TouchEvent) {
    const touch = event.touches[0] || event.changedTouches[0];
    clientX = touch.clientX;
    clientY = touch.clientY;
  } else {
    clientX = event.clientX;
    clientY = event.clientY;
  }

  return {
    x: (clientX - rect.left) * scaleX,
    y: (clientY - rect.top) * scaleY,
  };
};

// 开始绘画
const startDrawing = (event: MouseEvent) => {
  if (!props.isDrawer || props.disabled) return;

  isDrawing.value = true;
  const pos = getEventPos(event);
  currentStroke.value = [
    {
      x: pos.x,
      y: pos.y,
      color: currentColor.value,
      size: brushSize.value,
      timestamp: Date.now(),
    },
  ];

  drawPoint(pos.x, pos.y);
};

// 绘画过程
const draw = (event: MouseEvent) => {
  if (!isDrawing.value || !props.isDrawer || props.disabled) return;

  const pos = getEventPos(event);
  const point: DrawPoint = {
    x: pos.x,
    y: pos.y,
    color: currentColor.value,
    size: brushSize.value,
    timestamp: Date.now(),
  };

  currentStroke.value.push(point);
  drawLine(currentStroke.value[currentStroke.value.length - 2], point);
};

// 停止绘画
const stopDrawing = () => {
  if (!isDrawing.value) return;

  isDrawing.value = false;

  if (currentStroke.value.length > 0) {
    const stroke: DrawStroke = {
      points: [...currentStroke.value],
      color: currentColor.value,
      size: brushSize.value,
      id: Date.now().toString(),
    };

    gameStore.addStroke(stroke, true);
    emit("strokeAdded", stroke);
    currentStroke.value = [];
  }
};

// 触摸事件处理
const handleTouchStart = (event: TouchEvent) => {
  const touch = event.touches[0];
  const mouseEvent = new MouseEvent("mousedown", {
    clientX: touch.clientX,
    clientY: touch.clientY,
  });
  startDrawing(mouseEvent);
};

const handleTouchMove = (event: TouchEvent) => {
  const touch = event.touches[0];
  const mouseEvent = new MouseEvent("mousemove", {
    clientX: touch.clientX,
    clientY: touch.clientY,
  });
  draw(mouseEvent);
};

// 绘制点
const drawPoint = (x: number, y: number) => {
  if (!ctx.value) return;

  ctx.value.beginPath();
  ctx.value.arc(x, y, brushSize.value / 2, 0, 2 * Math.PI);
  ctx.value.fillStyle = currentColor.value;
  ctx.value.fill();
};

// 绘制线条
const drawLine = (from: DrawPoint, to: DrawPoint) => {
  if (!ctx.value) return;

  ctx.value.beginPath();
  ctx.value.moveTo(from.x, from.y);
  ctx.value.lineTo(to.x, to.y);
  ctx.value.strokeStyle = to.color;
  ctx.value.lineWidth = to.size;
  ctx.value.lineCap = "round";
  ctx.value.lineJoin = "round";
  ctx.value.stroke();
};

// 清除画布
const clearCanvas = () => {
  if (!ctx.value || !canvas.value) return;

  ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);
  gameStore.clearCanvas(true);
  emit("canvasCleared");
};

// 撤回最后一笔
const undoLastStroke = () => {
  if (!ctx.value || !canvas.value) return;

  // 移除最后一笔
  gameStore.removeLastStroke();
  // 重绘画布
  redrawCanvas();
};

// 计算是否可以撤回
const canUndo = computed(() => {
  return (
    gameStore.gameState.strokes.length > 0 && gameStore.gameState.isDrawing
  );
});

// 重绘所有笔画
const redrawCanvas = () => {
  if (!ctx.value || !canvas.value) return;

  ctx.value.clearRect(0, 0, canvas.value.width, canvas.value.height);

  gameStore.gameState.strokes.forEach((stroke) => {
    stroke.points.forEach((point, index) => {
      if (index === 0) {
        drawPoint(point.x, point.y);
      } else {
        drawLine(stroke.points[index - 1], point);
      }
    });
  });
};

// 监听画布尺寸变化
const resizeObserver = new ResizeObserver(() => {
  updateCanvasSize();
});

// 监听游戏状态变化
watch(
  () => gameStore.gameState.strokes,
  () => {
    redrawCanvas();
  },
  { deep: true }
);

onMounted(() => {
  if (canvas.value) {
    ctx.value = canvas.value.getContext("2d");
  }

  updateCanvasSize();
  window.addEventListener("resize", updateCanvasSize);

  if (canvasWrapper.value) {
    resizeObserver.observe(canvasWrapper.value);
  }
});

onUnmounted(() => {
  window.removeEventListener("resize", updateCanvasSize);
  resizeObserver.disconnect();
});
</script>

<style scoped>
.drawing-canvas-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.canvas-wrapper {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.drawing-tools {
  position: absolute;
  z-index: 10;
}

.tools-desktop {
  top: 10px;
  left: 10px;
}

.tools-mobile {
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  width: 95%;
  overflow-x: auto;
}

.tools-mobile .flex {
  flex-wrap: nowrap;
  min-width: max-content;
  padding: 4px;
}

.mobile-layout {
  height: 50vh;
}

.desktop-layout {
  height: 70vh;
}

/* 防止触摸滚动 */
.drawing-canvas-container {
  touch-action: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
</style>
